package gold.digger;

import gold.utils.InputUtil;

/**
 * Created by fanzhenyu02 on 2021/12/10.
 * common problem solver template.
 */
public class LC1191 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
//        分析最大子数组和可能的情况
//
//        子数组存在于单个数组内，此时最大和即为单个数组内的最大子数组和
//        子数组横跨两个数组，此时最大和即为单个数组内的最大前缀和加上最大后缀和
//        子数组横跨多个数组，此时要求单个数组总和大于0，此时最大和即为k-2个数组和加上最大前缀和加上最大后缀和

        int factor = 1000000007;

        public int kConcatenationMaxSum(int[] arr, int k) {
            long curSum = 0L, maxInnerSum = 0L, arrSum = 0L, maxPreSum = 0L, maxAfterSum = 0L, afterSum = 0L;
            for (int i = 0; i < arr.length; i++) {
                arrSum = (arrSum + arr[i]) % factor;
                maxPreSum = Math.max(maxPreSum, arrSum);

                if (curSum + arr[i] < arr[i]) curSum = arr[i] % factor;
                else curSum = (curSum + arr[i]) % factor;
                maxInnerSum = Math.max(maxInnerSum, curSum);
            }

            if (1 == k) return (int) maxInnerSum;
            if (arrSum > 0) arrSum = (arrSum * (k - 2)) % factor;
            else arrSum = 0;

            for (int i = arr.length - 1; i >= 0; i--) {
                afterSum = (afterSum + arr[i]) % factor;
                maxAfterSum = Math.max(maxAfterSum, afterSum);
            }

            return (int) ((Math.max(maxPreSum + maxAfterSum + arrSum, maxInnerSum)) % factor);
        }
    }

    public void run() {
        System.out.println(new Solution().kConcatenationMaxSum(InputUtil.toIntegerArray("[-5,4,-4,-3,5,-3]"), 5));
        System.out.println(new Solution().kConcatenationMaxSum(InputUtil.toIntegerArray("[1,2]"), 1));
        System.out.println(new Solution().kConcatenationMaxSum(InputUtil.toIntegerArray("[1,2]"), 3));
        System.out.println(new Solution().kConcatenationMaxSum(InputUtil.toIntegerArray("[1,-2,1]"), 5));
        System.out.println(new Solution().kConcatenationMaxSum(InputUtil.toIntegerArray("[-1,-2]"), 7));
    }

    public static void main(String[] args) throws Exception {
        LC1191 an = new LC1191();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
